<?php
class App_Order_Tuan 
{
    public static function hasJoined ($uid, $tuanNid)
    {
        return Data_Base::counts('app_order', array(
            array('tuanId', '=', $tuanNid), 
            array('uid', '=', $uid))
        );
    }

	// 团购任务数量
    public static function taskCount ($listWheres = array())
    {
        $orders = array();
        $query = DB::select(DB::expr("count(t.id) as count"))
            ->from(array('app_tuan', 't'))
            ->join(array('tiyu_goods', 'g'), 'LEFT')
            ->on('t.goodsId', '=', 'g.id');

        foreach ($listWheres as $rs)
        {
            if (is_array($rs))
            {
                $query->where($rs[0], $rs[1], $rs[2]);
            }
        }

        $count = $query->execute()->get('count');
        return $count;
    }



	// 团购任务列表
    public static function taskList ($offset, $limit, $listWheres = array())
    {
        $orders = array();
        $query = DB::select('t.*', array('g.name', 'goodsName'), 'g.shopId')
            ->from(array('app_tuan', 't'))
            ->join(array('tiyu_goods', 'g'), 'LEFT')
            ->on('t.goodsId', '=', 'g.id')
            ->order_by('t.created', 'desc');

        foreach ($listWheres as $rs)
        {
            if (is_array($rs))
            {
                $query->where($rs[0], $rs[1], $rs[2]);
            }
        }

        $query = $query->offset($offset)->limit($limit)->execute();

        foreach ($query as $rs)
        {
            $buyer = User::getUserFromUid($rs['createrUid'])->getUserInfo();

            $rs['title']          = utf8::substr($rs['goodsName'], 0, 50) . '...';
            $rs['shortTitle']     = utf8::substr($rs['title'], 0, 15) . '...';
            $rs['tuanMasterName'] = $buyer['userName'];
            $rs['tuanMasterIcon'] = $buyer['userIcon'];
            $rs['tuanMasterUid']  = $buyer['userUid'];
            $rs['shopName']       = App_Shop::name($rs['shopId']);
            $rs['tuanStatusName'] = self::tuanStatusName($rs['status']);

            $orders[] = $rs;
        }

        return $orders;
    }


	// 团购订单列表
	// @param array listWheres 订单查询条件
    public static function infoList ($offset, $limit, $listWheres = array())
    {
        $orders = array();
        $query = DB::select('a.*', 
                array('t.status', 'tuanStatus')
            )
            ->from(array('app_order', 'a'))
            ->join(array('app_tuan', 't'), 'LEFT')
            ->on('a.tuanId', '=', 't.id')
            ->order_by('a.changed', 'desc');

        foreach ($listWheres as $rs)
        {
            if (is_array($rs))
            {
                $query->where('a.'.$rs[0], $rs[1], $rs[2]);
            }
        }

        $query = $query->offset($offset)->limit($limit)->execute();

        foreach ($query as $rs)
        {
            $rs['statusName']     = App_Order::orderStatusName ($rs['status']);
            $rs['deliverName']    = App_Deliver::getName($rs['deliverId']);
            $rs['title']          = utf8::substr($rs['title'], 0, 50) . '...';
            $rs['shortTitle']     = utf8::substr($rs['title'], 0, 15) . '...';
            $rs['userName']       = User::getUserFromUid($rs['uid'])->getUserName();
            $rs['paymentName']    = App_Payment::name($rs['paymentId']);
            $rs['shopName']       = App_Shop::name($rs['shopId']);
            $rs['tuanStatusName'] = self::tuanStatusName($rs['tuanStatus']);

            $orders[] = $rs;
        }

        return $orders;
    }



    public static function detail ($nid)
    {
        $detail      = self::info($nid);
        $detail['goods'] = App_Goods::info($detail['goodsId']);
        $detail['orders'] = self::orders($nid);

        // 团长
        $createrUid = $detail['createrUid'];
        foreach ($detail['orders'] as & $order)
        {
            if ($order['uid'] == $createrUid)
            {
                $order['isCreater'] = 1;
                $detail['tuanMasterUid']  = $order['uid'];
                $detail['tuanMasterName'] = $order['userName'];
                $detail['tuanMasterIcon'] = $order['userIcon'];
            }
            else
                $order['isCreater'] = 0;
        }

        // 开团时间, 结束时间,还差几人
        $detail['startTime']   = $detail['created'];
        $detail['stopTime']    = $detail['startTime'] + 3600 * 24;
        $detail['wantPersons'] = $detail['tuanPersons'] - $detail['realPersons'];

        // 团购详情页地址
        $detail['buyUrl'] = url::site('/goods/tuan/'.$detail['goodsId'], 'http', FALSE);
        $detail['tuanStatusName'] = self::tuanStatusName($detail['status']);

        return $detail;
    }

    public static function orderPaid ($orderNo)
    {
        $order     = App_Order::detail($orderNo);
        $orderType = Arr::get($order, 'orderType');
        $tuanId    = Arr::get($order, 'tuanId');

        // 忽略非团购订单
        if (strtoupper($orderType) == 'NORMAL')
        {
            return;
        }

        // 生成团购
        if (empty($tuanId))
        {
            $createUid = Arr::get($order, 'uid');
            $created   = Arr::get($order, 'created');
            $arrGoods  = Arr::get($order, 'arrGoodsInfo');
            $goods     = Arr::get($arrGoods, 0);
            $goodsId   = Arr::get($goods['goods'], 'nid');
            $tuanPersons = App_Goods::getTuanPersons($goodsId);
            $status    = $tuanPersons > 1 ? 0 : 1;

            $row = array(
                'created'     => $created,
                'createrUid'  => $createUid,
                'status'      => $status,
                'tuanPersons' => $tuanPersons,
                'realPersons' => 1,
                'goodsId'     => $goodsId,
            );

            list($id, $rows) = DB::insert('app_tuan')
                ->columns(array_keys($row))
                ->values(array_values($row))
                ->execute();
            
            $tuanId = $id;
            self::updateOrderTuan($orderNo, $tuanId);
        }
        else
        // 更新团购实际人数
        {
            $realPersons = DB::select(DB::expr('count(distinct(`uid`)) as counts'))
                ->from('app_order')
                ->where('tuanId', '=', $tuanId)
                ->where('status', '=', 1)
                ->execute()
                ->get('counts');

            // 状态
            $update = array('realPersons' => $realPersons);
            $info = self::info ($tuanId);
            $tuanPersons = Arr::get($info, 'tuanPersons', 9999);
            if ($realPersons >= $tuanPersons)
            {
                $update['status'] = 1;
            }

            DB::update('app_tuan')
                ->set($update)
                ->where('id', '=', $tuanId)
                ->execute();
       }

       return $tuanId;
    }

    public static function updateOrderTuan($orderNo, $tuanId)
    {
        DB::update('app_order')
            ->set(array('tuanId' => $tuanId))
            ->where('orderNo', '=', $orderNo)
            ->execute();
    }

    public static function info ($tuanId)
    {
        $query = DB::select()
            ->from('app_tuan')
            ->where('id', '=', $tuanId)
            ->execute();

        return $query->current();
            
    }

    // 团购订单列表
    public static function orders ($nid)
    {
        $query = DB::select('o.*', 'u.userName', 'u.userIcon')
            ->from(array('app_order', 'o'))
            ->join(array('user_v2', 'u'), 'LEFT')
            ->on('o.uid', '=', 'u.uid')
            ->where('tuanId', '=', $nid)
            ->order_by('paidTime', 'asc')
            ->execute();

        $ret = array();
        foreach ($query as $rs)
        {
            $rs['statusName'] = App_Order::orderStatusName($rs['status']);
            $ret[] = $rs;
        }

        return $ret;
    }

    public static function progressStepStyle ($detail, $currUid)
    {
        $ret = array();
        $ret['progressStep1'] = '';
        $ret['progressStep2'] = '';
        $ret['progressStep3'] = '';
        $ret['progressStep4'] = '';

        if (empty($detail) || empty($detail['orders']))
        {
            $ret['progressStep1'] = 'active';
        }
        else if ($detail['status'] == 1)
        {
            $ret['progressStep4'] = 'active';
        }
        else 
        {
            $uids = array();
            foreach ($detail['orders'] as $o)
                $uids[] = $o['uid'];

            // 当前用户已经购买过
            if (in_array($currUid, $uids))
                $ret['progressStep3'] = 'active';
            else
            // 还没有购买过
                $ret['progressStep2'] = 'active';
        }

        return $ret;
    }

    public static function tuanStatusName ($tuanStatusId)
    {
        switch ($tuanStatusId)
        {
        case 0:
            return '进行中';
            break;

        case 1:
            return '成功';
            break;

        case 2:
        default:
            return '失败';
            break;
        }
    }

    public static function options_statusList ()
    {
        return array(
            0 => '进行中',
            1 => '成功',
            2 => '失败',
        );
    }
}
